var PORT = 3000;

var http = require('http');
var url=require('url');
var fs=require('fs');
var mine=require('./mine').types;
var path=require('path');
var httpProxy = require('http-proxy');
var zlib = require('zlib');
var notify = require('gulp-notify');
var plumber = require('gulp-plumber');
var gulp = require('gulp'),
    htmlmin = require('gulp-htmlmin')
    minifycss = require('gulp-minify-css'),
    concat = require('gulp-concat');
    uglify = require('gulp-uglify'),
    rename = require('gulp-rename');
//html压缩
gulp.task('minifyhtml', function () {
    var options = {
        removeComments: true,//清除HTML注释
        collapseWhitespace: true,//压缩HTML
        collapseBooleanAttributes: true,//省略布尔属性的值 <input checked="true"/> ==> <input />
        removeEmptyAttributes: true,//删除所有空格作属性值 <input id="" /> ==> <input />
        removeScriptTypeAttributes: true,//删除<script>的type="text/javascript"
        removeStyleLinkTypeAttributes: true,//删除<style>和<link>的type="text/css"
        minifyJS: true,//压缩页面JS
        minifyCSS: true//压缩页面CSS
    };
    gulp.src('html/*.html')
        .pipe(htmlmin(options))
        .pipe(plumber({errorHandler: notify.onError('Error: <%= error.message %>')}))
        .pipe(gulp.dest('runtime/html/'));
});

// 监听html文件变化
 gulp.watch('html/*.html', function(){
    gulp.run('minifyhtml');
 });
 
//合并压缩css
gulp.task('minifycss', function() {
    return gulp.src(['css/globle.css','css/main.css','css/Slist.css','css/transition.css','css/layer.css','!css/*.min.css'])      //压缩的文件
    	.pipe(concat('wmember.min.css'))
        .pipe(plumber({errorHandler: notify.onError('Error: <%= error.message %>')}))
        .pipe(gulp.dest('css/'))   //输出文件夹
        .pipe(minifycss());   //执行压缩
});

// Watch .css files
gulp.watch(['css/globle.css','css/main.css','css/Slist.css','css/transition.css','css/layer.css'], function(){
   gulp.run('minifycss');
});
//合并压缩 js目录外层的js
gulp.task('minifyjs', function() {
    return gulp.src(['js/app.js','js/start.js','!js/*.min.js'])
    	.pipe(concat('main.js')) //合并为main.js
        .pipe(rename({suffix: '.min'}))   //rename压缩后的文件名
        .pipe(plumber({errorHandler: notify.onError('Error: <%= error.message %>')}))
     	.pipe(uglify({
            //mangle: true,//类型：Boolean 默认：true 是否修改变量名
            mangle: {except: ['require' ,'exports' ,'module' ,'$']}//排除混淆关键字
         }))
        .pipe(gulp.dest('runtime/js/'));  //输出
});

 // Watch
 gulp.watch(['js/app.js','js/start.js'], function(){
	gulp.run('minifyjs');
 });
  
//压缩js/app目录下文件
gulp.task('minifyappjs', function() {
    return gulp.src(['js/app/*.js','!js/app/*.min.js'])
        .pipe(rename({suffix: '.min'}))   //rename压缩后的文件名
        .pipe(plumber({errorHandler: notify.onError('Error: <%= error.message %>')}))
         .pipe(uglify({
            //mangle: true,//类型：Boolean 默认：true 是否修改变量名
            mangle: {except: ['require' ,'exports' ,'module' ,'$']}//排除混淆关键字
        }))
        .pipe(gulp.dest('runtime/js/app/'));  //输出
});
//压缩js/lib目录下文件
gulp.task('minifylibjs', function() {
    return gulp.src(['js/lib/*.js','!js/lib/*.min.js'])
        .pipe(rename({suffix: '.min'}))   //rename压缩后的文件名
        .pipe(plumber({errorHandler: notify.onError('Error: <%= error.message %>')}))
         .pipe(uglify({
            //mangle: true,//类型：Boolean 默认：true 是否修改变量名
            mangle: {except: ['require' ,'exports' ,'module' ,'$']}//排除混淆关键字
        }))
        .pipe(gulp.dest('js/lib/'));  //输出
});
  // Watch
 gulp.watch(['js/app/*.js','!js/app/*.min.js'], function(){
    gulp.run('minifyappjs');
 });
  // Watch
 gulp.watch(['js/lib/*.js','!js/lib/*.min.js'], function(){
    gulp.run('minifylibjs');
 });
//执行
gulp.task('default', function() {
    gulp.start('minifyhtml','minifycss', 'minifyjs','minifyappjs','minifylibjs');
});
console.log("server starting...");
//app.js的读取
var app_config = fs.readFileSync("js/app.js",{encoding:'utf-8'});
app_config = app_config.slice(app_config.indexOf('{'));
eval("app_obj = " + app_config); //use eval instead of JSON.parse
console.log("service URL is：" + app_obj.api)

var proxy = httpProxy.createProxyServer({
    target: app_obj.api,   //接口地址
    // 下面的设置用于https
    // ssl: {
    //     key: fs.readFileSync('server_decrypt.key', 'utf8'),
    //     cert: fs.readFileSync('server.crt', 'utf8')
    // },
    // secure: false
});

proxy.on('error', function(err, req, res){
    res.writeHead(500, {
        'content-type': 'text/plain'
    });
    console.log(err);
    res.end('Something went wrong. And we are reporting a custom error message.');
});

var server = http.createServer(function (request, response) {
    var pathname = url.parse(request.url).pathname;
    //var realPath = path.join("main-pages", pathname); // 指定根目录
    var realPath = path.join("./", pathname);
    //console.log(pathname);
    //console.log(realPath);
    var ext = path.extname(realPath);
    ext = ext ? ext.slice(1) : 'unknown';

    //判断如果是接口访问，则通过proxy转发
    var reqUrl = request.url;
    //console.log("reqUrl IndexOf：" + reqUrl.indexOf("ajaxLoadFlag") + ",reqUrl====" + reqUrl);
    if(reqUrl.indexOf("ajaxLoadFlag") >= 0){
    	console.log("ajax请求发起：" + request.url);
    	//获取ajax提交的信息
		request.on("data",function(data){
		    //打印
		    console.log(decodeURIComponent(data));
		    console.log("");
		});
        proxy.web(request, response);
        return;
    }

    fs.exists(realPath, function (exists) {
    	if(realPath == ".\\" || realPath == ".\/"){
    		response.writeHead(302, {
                'Content-Type': contentType,
                "Location":"/index.html"
           });
           response.end();
    	}else if (!exists) {
            response.writeHead(404, {
                'Content-Type': 'text/plain'
            });

            response.write("This request URL " + pathname + " was not found on this server.");
            response.end();
        } else {
        	var contentType = mine[ext] || "text/plain";
        	if(contentType.indexOf("text/javascript") >= 0 || contentType.indexOf("css") >= 0  || contentType.indexOf("png") >= 0 ){
        		var acceptEncoding = request.headers['accept-encoding'];
			    var gzip;
			    
			    if(acceptEncoding != undefined && acceptEncoding.indexOf('gzip')!=-1){ // 判断是否需要gzip压缩
			        
			        gzip = zlib.createGzip();
			        
			        // 记得响应 Content-Encoding，告诉浏览器：文件被 gzip 压缩过
			        response.writeHead(200, {
			            'Content-Encoding': 'gzip'
			        });
			        fs.createReadStream(realPath).pipe(gzip).pipe(response);
			    
			    }else{
			
			        fs.createReadStream(realPath).pipe(response);
			    }
        	}else{
	            fs.readFile(realPath, "binary", function (err, file) {
	                if (err) {
	                    response.writeHead(500, {
	                        'Content-Type': 'text/plain'
	                    });
	                    response.end(err);
	                } else {
	                    response.writeHead(200, {
	                        'Content-Type': contentType
	                    });
	                    response.write(file, "binary");
	                    response.end();
	                }
	            });
            }
        }
    });
});
server.listen(PORT);
console.log("Server runing at port: " + PORT + ".");